//
//  BaseViewController.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/4/11.
//

#import "TGBaseVC.h"
#import "SDImageCache.h"

@interface TGBaseVC (){
    UIPanGestureRecognizer * _rightPan;
    BOOL _navStyleWhite;
}
@property (nonatomic, assign) ZLNavigationBarStyle barStyle;

@end

@implementation TGBaseVC

- (instancetype)init {
    if (self = [super init]) {
        self.statusBarStyle = UIStatusBarStyleLightContent;
        self.barStyle = ZLNavigationBarStyleOrigin;
    }
    return self;
}
- (void)setTitle:(NSString *)title {
    self.titleView.title = title;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.navigationController.viewControllers.firstObject == self) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }else {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }


}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self hbd_setNeedsUpdateNavigationBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.hbd_barShadowHidden = YES;
    self.hbd_extendedLayoutDidSet = YES;
    [self setNavStyleRed];
    self.view.backgroundColor = UIColorForBackground;
    if (@available(iOS 11, *)) {
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
- (void)setupNavigationItems{
    [super setupNavigationItems];
    switch (self.barStyle) {
        case ZLNavigationBarStyleOrigin:
            [self setNavBarTitColor:NavBarBarTintColor titleColor:UIColorWhite];
            break;
        case ZLNavigationBarStyleWhite:
            [self setNavBarTitColor:UIColorWhite titleColor:TitleBlackColor];
            break;
        case ZLNavigationBarStyleLightGray:
            [self setNavBarTitColor:UIColorForBackground titleColor:TitleBlackColor];
            break;
        default:
            break;
    }
}
- (void)setNavBarTitColor:(UIColor *)barColor titleColor:(UIColor *)titlColor {
    self.hbd_barTintColor = barColor;
    self.hbd_tintColor = titlColor;
    self.titleView.tintColor = titlColor;
}
- (void)setNavStyleBlue{
    self.barStyle = ZLNavigationBarStyleOrigin;
    self.statusBarStyle = UIStatusBarStyleLightContent;
    [self setNavBarTitColor:GlobalBarTinColor titleColor:UIColorWhite];
}
-  (void)setNavStyleRed{
    self.barStyle = ZLNavigationBarStyleOrigin;
    self.statusBarStyle = UIStatusBarStyleLightContent;
    [self setNavBarTitColor:GlobalBarRedTinColor titleColor:UIColorWhite];
//    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:NavBarTitleFont};
}

- (void)setNavStyleRedAndBackBtn {
    self.barStyle = ZLNavigationBarStyleOrigin;
    self.statusBarStyle = UIStatusBarStyleLightContent;
    [self setNavBarTitColor:GlobalBarRedTinColor titleColor:UIColorWhite];
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:UIColorWhite,NSFontAttributeName:NavBarTitleFont};
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithImage:kImage(@"back_white_icon") target:self action:@selector(backActionForNavigation:)]];
}

///白色模式并带黑色的返回那妞
- (void)setNavStyleWhiteAndBackBtn{
    self.statusBarStyle = UIStatusBarStyleDefault;
    self.barStyle = ZLNavigationBarStyleWhite;
    [self setNavBarTitColor:UIColorWhite titleColor:TitleBlackColor];
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:TitleBlackColor,NSFontAttributeName:NavBarTitleFont};
    UIImage *img = kImage(@"black_back_icon");
    if (!img) {
        return;
    }
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithImage:img target:self action:@selector(backActionForNavigation:)]];
}
- (void)setNavStyleWhite {
    self.statusBarStyle = UIStatusBarStyleDefault;
    self.barStyle = ZLNavigationBarStyleWhite;
    [self setNavBarTitColor:UIColorWhite titleColor:TitleBlackColor];
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:TitleBlackColor,NSFontAttributeName:NavBarTitleFont};

}
- (void)setNavStyleLightGray {
    self.barStyle = ZLNavigationBarStyleLightGray;
    [self setNavBarTitColor:UIColorForBackground titleColor:TitleBlackColor];
}
-(void)setNavStyleLightGrayAndBackBtn{
    self.barStyle = ZLNavigationBarStyleLightGray;
    [self setNavBarTitColor:UIColorForBackground titleColor:TitleBlackColor];
    self.hbd_titleTextAttributes = @{NSForegroundColorAttributeName:TitleBlackColor,NSFontAttributeName:NavBarTitleFont};
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithImage:kImage(@"black_back_icon") target:self action:@selector(backActionForNavigation:)]];
}

- (void)pushViewController:(id)vc complent:(void (^)(void))completion {
    if ([vc isKindOfClass: [UIViewController class]]) {
        [self.navigationController qmui_pushViewController:vc animated:YES completion:completion];
    }else if ([vc isKindOfClass:[NSString class]]){
        [self.navigationController qmui_pushViewController: [[NSClassFromString(vc) alloc] init] animated:YES completion:completion];
    }
    
}
- (void)popToViewController:(NSString *)className  animated:(BOOL)animated {
    if (className==nil) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    for (UIViewController *v in  self.navigationController.viewControllers) {
        if ([v isKindOfClass:NSClassFromString(className)]) {
            [[self navigationController] popToViewController:v animated:animated];
            return;
        }
    }
    [self.navigationController popViewControllerAnimated:animated];
}
- (void)popToViewController:(NSString *)className {
    for (UIViewController *v in  self.navigationController.viewControllers) {
        if ([v isKindOfClass:NSClassFromString(className)]) {
            [[self navigationController] popToViewController:v animated:YES];
            return;
        }
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)backActionForNavigation:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setLeftButtonBlackAction:(SEL)selct {
    [self setLeftBarButtonImage:@"black_back_icon" selector:selct];
}
-(void)setLeftButtonWhiteAction:(SEL)selct {
    [self setLeftBarButtonImage:@"back_white_icon" selector:selct];
}

- (void)setLeftBarButtonTitle:(NSString *)title selector:(SEL)sel{
    if (sel==nil) {
        sel = @selector(backActionForNavigation:);
    }
    if (!title) {
        return;
    }
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithTitle:title target:self action:sel]];

}

- (void)setLeftBarButtonTitle:(NSString *)title selector:(SEL)sel haveBack:(BOOL)haveBack {
    if (haveBack && sel == nil) {
        sel = @selector(backActionForNavigation:);
    }
    
    QMUIButton *button = [QMUIButton buttonWithType:UIButtonTypeCustom];
    button.imagePosition = QMUIButtonImagePositionLeft;
    button.spacingBetweenImageAndTitle = 15;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:UIColorBlack forState:UIControlStateNormal];
    button.titleLabel.font = TGSemiboldFont(18);
    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    if (haveBack) {
        [button setImage:kImage(@"black_back_icon") forState:UIControlStateNormal];
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)setLeftWhiteBackBarButtonTitle:(NSString *)title selector:(SEL)sel haveBack:(BOOL)haveBack {
    if (haveBack && sel == nil) {
        sel = @selector(backActionForNavigation:);
    }
    
    QMUIButton *button = [QMUIButton buttonWithType:UIButtonTypeCustom];
    button.imagePosition = QMUIButtonImagePositionLeft;
    button.spacingBetweenImageAndTitle = 15;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:UIColorWhite forState:UIControlStateNormal];
    button.titleLabel.font = TGSemiboldFont(18);
    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    if (haveBack) {
        [button setImage:kImage(@"new_back_white_icon") forState:UIControlStateNormal];
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)setLeftBarButtonImage:(NSString *)image selector:(SEL)sel {
    if (sel==nil) {
        sel = @selector(backActionForNavigation:);
    }
    UIImage *img = kImage(image);
    if (!img) {
        return;
    }
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithImage:img target:self action:sel]];
}

- (void)setLeftQMNavBarButtonImage:(NSString *)image selector:(SEL)sel {
    if (sel==nil) {
        sel = @selector(backActionForNavigation:);
    }
    UIImage *img = kImage(image);
    if (!img) {
        return;
    }
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem qmui_itemWithButton:[[QMUINavigationButton alloc] initWithImage:img] target:self action:sel]];
   
}

- (void)setRightQMNavBarButtonImage:(NSString *)image selector:(SEL)sel {
    
    UIImage *img = kImage(image);
    if (!img) {
        return;
    }
     self.navigationItem.rightBarButtonItems = @[[UIBarButtonItem qmui_itemWithButton:[[QMUINavigationButton alloc] initWithImage:img] target:self action:sel]];
}


- (void)setRightBarButtonImage:(NSString *)image selector:(SEL)sel {
    
    UIImage *img = [kImage(image) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    if (!img) {
        return;
    }
    self.navigationItem.rightBarButtonItems =  @[[UIBarButtonItem qmui_itemWithImage:img target:self action:sel]];//
}
- (void)setRightBarButtonTitle:(NSString *)title selector:(SEL)sel {
    if (!title) {
        return;
    }
    self.navigationItem.rightBarButtonItems = @[[UIBarButtonItem qmui_itemWithTitle:title target:self action:sel]];
}
-(UIStatusBarStyle)preferredStatusBarStyle;
{
    return self.statusBarStyle;
}

-(void)setDisableRightSwipe:(BOOL)disableRightSwipe {
    _disableRightSwipe = disableRightSwipe;
    if (_rightPan) {
        [self.view removeGestureRecognizer:_rightPan];
        _rightPan = nil;
    }
    if (_disableRightSwipe) {
        id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
        [self.view addGestureRecognizer:pan];
        _rightPan = pan;
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%@ 🔴视图释放",[self class]);
}
- (void)cancelTask {
    if (self.baseDataTask) {
        [self.baseDataTask cancel];
        self.baseDataTask = nil;
    }
    [self cancelAllSessionDataTask];
}
- (NSMutableArray *)sessionDataTaskMArr {
    if (_sessionDataTaskMArr == nil) {
        _sessionDataTaskMArr = [NSMutableArray array];
    }
    return _sessionDataTaskMArr;
}
- (void)addSessionDataTask:(NSURLSessionDataTask *)task {
    if (task == nil) {return;}
    [self.sessionDataTaskMArr addObject:[NSString stringWithFormat:@"%@",task.currentRequest.URL.absoluteString]];
}

- (void)removeSessionDataTask:(NSURLSessionDataTask *)task {
    [self.sessionDataTaskMArr removeObject:[NSString stringWithFormat:@"%@",task.currentRequest.URL.absoluteString]];
}
- (void)cancelAllSessionDataTask {
    if (self.sessionDataTaskMArr.count <= 0) {
        return;
    }
    //4.12注释，随后调试接口时放开
//    for (NSString *dataTask in self.sessionDataTaskMArr) {
//        [TGAPIRequest cancelRequestWithURL:dataTask];
//    }
    [self.sessionDataTaskMArr removeAllObjects];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}


//
//- (UIImage *)qmui_navigationBarBackgroundImage {
//    if (self.barStyle == ZLNavigationBarStyleOrigin) {
//        return [UIImage qmui_imageWithColor:UIColorRed];
//    } else if (self.barStyle == ZLNavigationBarStyleBlue) {
//        return [UIImage qmui_imageWithColor:ZBDefalutColor];
//    } else if (self.barStyle == ZLNavigationBarStyleWhite) {
//        return [UIImage qmui_imageWithColor:UIColorWhite];
//    }else if (self.barStyle == ZLNavigationBarStyleLightGray) {
//        return [UIImage qmui_imageWithColor:RGB(248, 248, 248)];
//    }else if (self.barStyle == ZLNavigationBarStyleGray) {
//        return [UIImage qmui_imageWithColor:UIColorForBackground];
//    }else if (self.barStyle == ZLNavigationBarStyleTransparency) {
//        return [UIImage qmui_imageWithColor:UIColorClear];
//    }
//    else {
//        return NavBarBackgroundImage;
//    }
//}
//
//- (UIImage *)qmui_navigationBarShadowImage {
//    return NavBarShadowImage;
//}
//
- (UIColor *)qmui_navigationBarTintColor {
    if (self.barStyle == ZLNavigationBarStyleOrigin) {
        return UIColorWhite;
    } else if (self.barStyle == ZLNavigationBarStyleBlue) {
        return UIColorWhite;
    } else if (self.barStyle == ZLNavigationBarStyleWhite) {
        return TitleBlackColor;
    }else if (self.barStyle == ZLNavigationBarStyleLightGray) {
        return TitleBlackColor;
    } else {
        return TitleBlackColor;
    }
}
//
//- (UIColor *)qmui_titleViewTintColor {
//    return [self qmui_navigationBarTintColor];
//}
//
//#pragma mark - <QMUICustomNavigationBarTransitionDelegate>
//
//- (NSString *)customNavigationBarTransitionKey {
//    // 不同的 barStyle 返回不同的 key，这样在不同 barStyle 的界面之间切换时就能使用自定义的 navigationBar 样式，会带来更好的视觉体验
//    // 返回 nil 则表示当前界面没有修改过导航栏样式
//    // 注意，如果你使用配置表，建议打开 AutomaticCustomNavigationBarTransitionStyle，由 QMUI 自动帮你判断是否需要使用自定义样式，这样就无需再实现 customNavigationBarTransitionKey 方法。QMUI Demo 里为了展示接口的使用，没有打开这个开关。
//    return [NSString qmui_stringWithNSInteger:self.barStyle];
//
////    return self.barStyle == QDNavigationBarStyleOrigin ? nil : [NSString qmui_stringWithNSInteger:self.barStyle];
//}
///首页左边位置按钮
-(void)setLeftWithTarget:(id)target action:(SEL)action leftImageString:(NSString *)str title:(NSString *)title image:(UIImage *)image maxWith:(CGFloat)maxWith{
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        UIImageView *leftImageView = nil;
//        if (str)
        {
            leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (44-14)/2 - 2, 14, 17)];
//            leftImageView.layer.cornerRadius = 11;
//            leftImageView.clipsToBounds = YES;
//            [leftImageView ld_setImageWithAutoURL:str placeholderImage:UIImageMake(@"home_touxiang_logo")];
            leftImageView.image = kImage(str);
            [view addSubview:leftImageView];
        }
        QMUIButton *button = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [view addSubview:button];
        button.userInteractionEnabled = NO;
    
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
        [view addGestureRecognizer:tap];
    
//          [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
          [button setTitle:title forState:UIControlStateNormal];
          [button setTitleColor:DeepBlackColor forState:0];
          button.titleLabel.font = TGAutoFont(14);
//          [button setImage: [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
          button.spacingBetweenImageAndTitle = 5;
          button.imagePosition =  QMUIButtonImagePositionRight;
          [button sizeToFit];

          if (button.width > maxWith) {
              button.width = maxWith;
           }
           button.height =  44;
           button.left = leftImageView.right + 5;
        CGFloat space = 0;
        space = 5 + leftImageView.width;
        space += button.width;
        view.frame = CGRectMake(0, 0, space, 44);
    
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:view]];
}
-(void )setLeftWithTarget:(id)target action:(SEL)action rightImageString:(NSString *)str title:(NSString *)title image:(UIImage *)image maxWith:(CGFloat)maxWith {
    [self setLeftWithTarget:target action:action rightImageString:str title:title titleColor:DeepBlackColor image:image maxWith:maxWith];
}

-(void )setLeftWithTarget:(id)target action:(SEL)action rightImageString:(NSString *)str title:(NSString *)title titleColor:(UIColor *)titleColor image:(UIImage *)image maxWith:(CGFloat)maxWith {
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

    QMUIButton *button = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [view addSubview:button];
    button.userInteractionEnabled = NO;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:tap];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:titleColor forState:0];
    button.titleLabel.font = TGSemiboldFont(15);
//    button.lineBreakMode = NSLineBreakByTruncatingTail;
    
    button.spacingBetweenImageAndTitle = 5;
    button.imagePosition = QMUIButtonImagePositionRight;
    [button sizeToFit];
    
    if (button.width > maxWith) {
        button.width = maxWith;
    }
    button.height = 44;
    button.left = 0;

    UIImageView *leftImageView = [[UIImageView alloc] init];
    leftImageView.image = kImage(str);
    leftImageView.contentMode = UIViewContentModeScaleAspectFit;
    leftImageView.frame = CGRectMake(button.right+2, (44-15)/2+1, 15, 15);
    [view addSubview:leftImageView];

    CGFloat space = 0;
    space = leftImageView.width + 5;
    space += button.width;
    view.frame = CGRectMake(0, 0, space, 44);
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:view]];
}

@end
